package com.tanhua.server.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.util.RelativeDateFormat;
import com.tanhua.common.util.UserThreadLocal;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.service.QuanZiService;
import com.tanhua.server.service.UserInfoService;
import com.tanhua.server.service.UserService;
import com.tanhua.server.vo.CommentVo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.QuanZiVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@Service
public class QuanZiServiceImpl implements QuanZiService {
    @Autowired
    private UserService userService;
    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private PicUploadService picUploadService;

    @Override
    public PageResult queryPublishList(Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        User user = UserThreadLocal.get();

        //quanziVo中跟 文章 相关的部分数据去mongodb中查询publish表
        PageInfo<Publish> publishPageInfo = quanZiApi.queryPublishList(user.getId(), page, pageSize);
        List<Publish> records = publishPageInfo.getRecords();

        List<QuanZiVo> quanZiVoList = new ArrayList<>(records.size());
        QuanZiVo quanZiVo;
        for (Publish publish : records) {
            quanZiVo = new QuanZiVo();
            quanZiVo.setId(publish.getId().toHexString());
            quanZiVo.setTextContent(publish.getText());
            quanZiVo.setImageContent(publish.getMedias().toArray(new String[]{}));
            quanZiVo.setUserId(publish.getUserId());
            quanZiVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));

            quanZiVoList.add(quanZiVo);
        }

        //quanziVo中跟 用户 相关的部分数据去mysql中查询userInfo表
        List<Object> userIdList = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfoList = userInfoService.queryUserInfoByUserIdList(userIdList);
        for (QuanZiVo quanZiVo1 : quanZiVoList) {
            //找到对应的用户信息
            for (UserInfo userInfo : userInfoList) {
                if (quanZiVo1.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    this.fillUserInfoToQuanZiVo(userInfo, quanZiVo1);
                    break;
                }
            }
        }

        pageResult.setItems(quanZiVoList);
        return pageResult;
    }

    @Override
    public PageResult queryRecommendPublishList(Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        User user = UserThreadLocal.get();

        PageInfo<Publish> pageInfo = quanZiApi.queryRecommendPublishList(user.getId(), page, pageSize);
        List<Publish> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
            return pageResult;
        }

        pageResult.setItems(this.fillQuanZiVo(records));
        return pageResult;
    }

    /**
     * 填充用户信息
     *
     * @param userInfo
     * @param quanZiVo
     */
    private void fillUserInfoToQuanZiVo(UserInfo userInfo, QuanZiVo quanZiVo) {
        BeanUtil.copyProperties(userInfo, quanZiVo, "id");
        quanZiVo.setGender(userInfo.getSex().name().toLowerCase());
        quanZiVo.setTags(StringUtils.split(userInfo.getTags(), ','));

        quanZiVo.setCommentCount(0); //TODO 评论数
        quanZiVo.setDistance("1.2公里"); //TODO 距离
        User user = UserThreadLocal.get();
        quanZiVo.setHasLiked(this.quanZiApi.queryUserIsLike(user.getId(), quanZiVo.getId()) ? 1 : 0); //是否点赞（1是，0否）
        quanZiVo.setLikeCount(this.quanZiApi.queryCommentLikeCount(quanZiVo.getId())); //点赞数
        quanZiVo.setHasLoved(this.quanZiApi.queryUserIsLoveComment(user.getId(), quanZiVo.getId()) ? 1 : 0); //TODO 是否喜欢（1是，0否）
        quanZiVo.setLoveCount(Convert.toInt(this.quanZiApi.queryLoveCount(quanZiVo.getId()))); //TODO 喜欢数
    }

    /**
     * 根据查询到的publish集合填充QuanZiVo对象
     *
     * @param records
     * @return
     */
    private List<QuanZiVo> fillQuanZiVo(List<Publish> records) {
        List<QuanZiVo> quanZiVoList = new ArrayList<>();
        records.forEach(publish -> {
            QuanZiVo quanZiVo = new QuanZiVo();
            quanZiVo.setId(publish.getId().toHexString());
            quanZiVo.setTextContent(publish.getText());
            quanZiVo.setImageContent(publish.getMedias().toArray(new String[]{}));
            quanZiVo.setUserId(publish.getUserId());
            quanZiVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));

            quanZiVoList.add(quanZiVo);
        });

        //查询用户信息
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByUserIdList(userIds);
        for (QuanZiVo quanZiVo : quanZiVoList) {
            //找到对应的用户信息
            for (UserInfo userInfo : userInfoList) {
                if (quanZiVo.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    this.fillUserInfoToQuanZiVo(userInfo, quanZiVo);
                    break;
                }
            }
        }

        return quanZiVoList;
    }


    @Override
    public String savePublish(String textContent, MultipartFile[] imageContent, String location, String longitude, String latitude) {
        User user = UserThreadLocal.get();

        Publish publish = new Publish();
        publish.setText(textContent);
        publish.setLocationName(location);
        publish.setLongitude(longitude);
        publish.setLatitude(latitude);
        publish.setUserId(user.getId());
        publish.setSeeType(1);

        List<String> picUrls = new ArrayList<>(imageContent.length);
        for (MultipartFile multipartFile : imageContent) {
            PicUploadResult picUploadResult = picUploadService.upload(multipartFile);
            picUrls.add(picUploadResult.getName());
        }

        publish.setMedias(picUrls);

        return quanZiApi.savePublish(publish);
    }

    @Override
    public Integer disLikeComment(String publishId) {
        User user = UserThreadLocal.get();

        Boolean result = this.quanZiApi.disLikeComment(user.getId(), publishId);
        if (result) {
            return this.quanZiApi.queryCommentLikeCount(publishId);
        }
        return null;
    }

    @Override
    public Integer likeComment(String publishId) {
        User user = UserThreadLocal.get();

        Boolean result = this.quanZiApi.likeComment(user.getId(), publishId);
        if (result) {
            return this.quanZiApi.queryCommentLikeCount(publishId);
        }
        return null;
    }

    @Override
    public Integer loveComment(String publishId) {
        User user = UserThreadLocal.get();

        if (this.quanZiApi.loveComment(user.getId(), publishId)) {
            return Convert.toInt(this.quanZiApi.queryLoveCount(publishId));
        }

        return null;
    }

    @Override
    public Integer unLoveComment(String publishId) {
        User user = UserThreadLocal.get();

        if (this.quanZiApi.disLoveComment(user.getId(), publishId)) {
            return Convert.toInt(this.quanZiApi.queryLoveCount(publishId));
        }

        return null;
    }

    @Override
    public QuanZiVo queryById(String publishId) {
        Publish publish = this.quanZiApi.queryPublishById(publishId);
        if (publish == null) {
            return null;
        }
        return this.fillQuanZiVo(Collections.singletonList(publish)).get(0);
    }

    @Override
    public Boolean saveComment(String publishId, String content) {
        User user = UserThreadLocal.get();
        return quanZiApi.saveComment(user.getId(), publishId, content);
    }

    @Override
    public PageResult listComments(String publishId, Integer page, Integer pageSize) {
        User user = UserThreadLocal.get();
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        PageInfo<Comment> commentPageInfo = this.quanZiApi.listCommentByPublishId(publishId, page, pageSize);
        List<Comment> records = commentPageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
            return pageResult;
        }

        List<Object> userIdList = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByUserIdList(userIdList);

        List<CommentVo> commentVoList = new ArrayList<>(records.size());

        CommentVo commentVo = new CommentVo();
        records.forEach(comment -> {
            commentVo.setId(comment.getId().toHexString());
            commentVo.setContent(comment.getContent());
            commentVo.setCreateDate(DateUtil.format(new Date(comment.getCreated()), "HH:mm"));
            //是否点赞
            commentVo.setHasLiked(this.quanZiApi.queryUserIsLike(user.getId(), commentVo.getId()) ? 1 : 0);
            //点赞数
            commentVo.setLikeCount(Convert.toInt(this.quanZiApi.queryCommentLikeCount(commentVo.getId())));

            for (UserInfo userInfo : userInfoList) {
                if (ObjectUtil.equals(userInfo.getUserId(), comment.getUserId())) {
                    commentVo.setAvatar(userInfo.getLogo());
                    commentVo.setNickname(userInfo.getNickName());
                    break;
                }
            }
            commentVoList.add(commentVo);
        });

        pageResult.setItems(commentVoList);
        return pageResult;
    }
}
